package cn.team11.smarteye.base;

import android.Manifest;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Build;
import android.os.Bundle;
import android.os.IBinder;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.view.WindowManager;

import cn.team11.sds.dayi.R;
import com.eques.icvss.utils.ResultCode;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.lang.ref.WeakReference;
import java.util.List;

import cn.team11.smarteye.activity.InComingActiviity;
import cn.team11.smarteye.bean.CateyeEvent;
import cn.team11.smarteye.misc.SConstants;
import cn.team11.smarteye.misc.SystemBarTintManager;
import cn.team11.smarteye.misc.SystemUiHider;
import cn.team11.smarteye.service.CatEyeService;
import cn.team11.smarteye.utils.ToastUtil;
import permissions.dispatcher.NeedsPermission;
import permissions.dispatcher.OnShowRationale;
import permissions.dispatcher.PermissionRequest;
import permissions.dispatcher.RuntimePermissions;

/**
 * Created by Yang on 2017/10/12.
 */
@RuntimePermissions
public abstract class BaseActivity<T extends BasePresenter> extends AppCompatActivity implements BaseView<T>{

    protected T mBasePresenter;
    private SystemBarTintManager tintManager;
    private WeakReference<SystemUiHider> systemUiHiderWeakReference;

    private ServiceConnection mServiceConn;
    protected CatEyeService mCateyeService;

    protected int[] getOverridePendingTransition() {
        return new int[]{R.anim.slide_in_right, R.anim.slide_out_left};
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mServiceConn = new CateyeServiceConnection(this);
        //绑定猫眼服务
        bindCateyeService();

        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP){
            BaseActivityPermissionsDispatcher.checkPhoneStatePermissionWithCheck(this);
        }
    }

    public abstract void init();

    public abstract void onLoginResult(boolean result);

    public abstract void onNetAvailable(boolean isAvailable);

    public abstract void onCateyeServiceBinded();

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    protected void onStart() {
        super.onStart();
        if (mBasePresenter != null) mBasePresenter.start();
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mBasePresenter != null) mBasePresenter.destroy();
        if (EventBus.getDefault().isRegistered(this))
            EventBus.getDefault().unregister(this);
        //解绑猫眼服务
        unbindCateyeService();
    }

    @Override
    protected void onStop() {
        super.onStop();
    }

    public void initSystemBar() {

        overridePendingTransition(getOverridePendingTransition()[0], getOverridePendingTransition()[1]);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT && Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
            tintManager = new SystemBarTintManager(this);
            setSystemBarTintEnable(true);
        }
        handleSystemBar(false,100);
    }


    public void finishExt() {
        final int count = getSupportFragmentManager().getBackStackEntryCount();
        if (count>0){
            getSupportFragmentManager().popBackStack();
        } else {
            finish();
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
            //overridePendingTransition(R.anim.slide_in_left_without_interpolator, R.anim.slide_out_right_without_interpolator);
        }
    }


    /**
     * 弹出所有fragment，并结束当前activity
     * */
    public void finishAll(){
        popAllFragmentStack();
        finishExt();
    }

    @NeedsPermission(Manifest.permission.READ_PHONE_STATE)
    void checkPhoneStatePermission(){

    }


    @Override
    public void showToast(int toastType, String str) {
        switch (toastType){
            case ToastUtil.NORMAL_TOAST://normal
                ToastUtil.showToast(str);
                break;
            case ToastUtil.NEGATIVE_TOAST://negative
                ToastUtil.showNegativeToast(str);
                break;
            case ToastUtil.POSITIVE_TOAST://positive
                ToastUtil.showPositiveToast(str);
        }
    }

    /**
     * 用于隐藏系统状态栏
     */
    private void checkSystemHider() {
        if (systemUiHiderWeakReference == null
                || systemUiHiderWeakReference.get() == null) {
            systemUiHiderWeakReference = new WeakReference<>(new SystemUiHider(getWindow().getDecorView(), true));
        }
    }

    public void showSystemBar(boolean show, final long delayTime) {
        checkSystemHider();
        systemUiHiderWeakReference.get().setSupportAutoHide(!show);
        if (show) {
            systemUiHiderWeakReference.get().show();
        } else {
            systemUiHiderWeakReference.get().delayedHide(delayTime);
        }
    }

    public void handleSystemBar(boolean port, final long delay) {
        WindowManager.LayoutParams attrs = getWindow().getAttributes();
        if (port) {
            showSystemUI();
        } else {
            hideSystemUI();
        }
        getWindow().setAttributes(attrs);
        checkSystemHider();
        showSystemBar(port, delay);
        //状态栏的背景色
        setSystemBarTintEnable(port);
    }

    // This snippet hides the system bars.
    protected void hideSystemUI() {
        // Set the IMMERSIVE flag.
        // Set the content to appear under the system bars so that the content
        // doesn't resize when the system bars hide and show.
        getWindow().getDecorView().setSystemUiVisibility(
                View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                        | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                        | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                        | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION // hide nav bar
                        | View.SYSTEM_UI_FLAG_FULLSCREEN // hide status bar
                        | View.SYSTEM_UI_FLAG_IMMERSIVE);
    }

    // This snippet shows the system bars. It does this by removing all the flags
// except for the ones that make the content appear under the system bars.
    protected void showSystemUI() {
        getWindow().getDecorView().setSystemUiVisibility(
                View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                        | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                        | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
        if (systemUiHiderWeakReference != null && systemUiHiderWeakReference.get() != null) {
            systemUiHiderWeakReference.get().removeDelayRunnable();
        }
    }

    protected void setSystemBarTintEnable(boolean enable) {
        if (tintManager != null)
            tintManager.setStatusBarTintEnabled(enable);
    }

    @Override
    public void onBackPressed() {
        if (checkExtraChildFragment()) {
            return;
        } else if (checkExtraFragment())
            return;

        super.onBackPressed();

    }


    /**
     * 检查是否有子{@link Fragment}
     *
     * @return
     */
    protected boolean checkExtraChildFragment() {
        FragmentManager fm = getSupportFragmentManager();
        List<Fragment> list = fm.getFragments();
        if (list == null || list.size() == 0)
            return false;
        for (Fragment frag : list) {
            if (frag != null && frag.isVisible()) {
                FragmentManager childFm = frag.getChildFragmentManager();
                if (childFm != null && childFm.getBackStackEntryCount() > 0) {
//                    childFm.popBackStack();
                    childFm.popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE);
                    return true;
                }
            }
        }
        return false;
    }

    /**
     * @return
     */
    protected boolean checkExtraFragment() {
        final int count = getSupportFragmentManager().getBackStackEntryCount();
        if (count > 0) {
            getSupportFragmentManager().popBackStack();
            return true;
        } else return false;
    }

    /**
     * 弹出所有 {@link Fragment}
     *
     * @return
     */
    protected void popAllFragmentStack() {
        FragmentManager fm = getSupportFragmentManager();
        for (int i = 0; i < fm.getBackStackEntryCount(); ++i) {
            fm.popBackStack();
        }
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onLoginRet(CateyeEvent.ResultLogin result) {
        if (result.code == ResultCode.SUCCESS){
            //登录成功
            onLoginResult(true);
        } else {
            onLoginResult(false);
            showToast(ToastUtil.NEGATIVE_TOAST, "登录失败");
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onNetworkChanged(CateyeEvent.NetworkEvent event){
        onNetAvailable(event.isConnected);
        if (!event.isConnected)
            showToast(ToastUtil.NEGATIVE_TOAST, getString(R.string.network_disconnected));
    }

    public void bindCateyeService(){
        bindService(new Intent(this, CatEyeService.class), mServiceConn, Context.BIND_AUTO_CREATE);
    }

    public void unbindCateyeService(){
        if (mServiceConn != null)
            unbindService(mServiceConn);
    }

    @OnShowRationale(Manifest.permission.READ_PHONE_STATE)
    public void showRationalePhoneState(final PermissionRequest request){
        new AlertDialog.Builder(this)
                .setMessage(R.string.read_state_reason)
                .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        request.proceed();
                    }
                })
                .setNegativeButton(R.string.denied, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        request.cancel();
                    }
                }).show();

    }



    class CateyeServiceConnection implements ServiceConnection {

        private Context context;

        public CateyeServiceConnection(Context context) {
            this.context = context;
        }

        @Override
        public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
            mCateyeService = ((CatEyeService.CateyeServiceBinder)iBinder).getService();
            if (mCateyeService != null){
                onCateyeServiceBinded();
            }
        }

        @Override
        public void onServiceDisconnected(ComponentName componentName) {
            mCateyeService = null;
        }
    }



    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP){
            BaseActivityPermissionsDispatcher.onRequestPermissionsResult(this, requestCode, grantResults);
        }
    }
}
